package com.yqh.discovery.impl;

import com.yqh.Constant;
import com.yqh.ServiceConfig;
import com.yqh.discovery.AbstractRegistry;
import com.yqh.utils.NetUtils;
import com.yqh.utils.zookeeper.ZookeeperNode;
import com.yqh.utils.zookeeper.ZookeeperUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooKeeper;

import java.net.InetSocketAddress;

/**
 * @author 阳秋豪
 * @createTime 2024/3/1
 */
@Slf4j
public class NacosRegistry extends AbstractRegistry {
    // 维护一个 zookeeper 实例
    private final ZooKeeper zookeeper;

    public NacosRegistry() {
        this.zookeeper = ZookeeperUtils.createZookeeper();
    }

    public NacosRegistry(String connectString, int timeout) {
        this.zookeeper = ZookeeperUtils.createZookeeper(connectString, timeout);
    }

    @Override
    public void register(ServiceConfig<?> service) {
        // 服务的节点路径
        String parentNodePath = Constant.BASE_PROVIDERS_PATH + "/" + service.getInterfaceProvider().getName();
        // 如果服务节点不存在，则创建新的服务节点（持久节点）
        if (!ZookeeperUtils.exists(zookeeper, parentNodePath, null)) {
            ZookeeperNode zookeeperNode = new ZookeeperNode(parentNodePath, null);
            ZookeeperUtils.createNode(zookeeper, zookeeperNode, null, CreateMode.PERSISTENT);
        }
        // 创建本机的临时节点路径 -- 父节点路径 + ip:port
        // 服务提供方的接口一般自己设定，我们还需要一个获取 ip 的方法
        // ip 我们通常是需要一个局域网 ip，不是 127.0.0.1，也不是 ipv6
        // TODO -- 后续处理端口的问题
        String nodePath = parentNodePath + "/" + NetUtils.getIp() + ":" + 8088;
        if (!ZookeeperUtils.exists(zookeeper, nodePath, null)) {
            ZookeeperNode zookeeperNode = new ZookeeperNode(nodePath, null);
            ZookeeperUtils.createNode(zookeeper, zookeeperNode, null, CreateMode.EPHEMERAL);
        }
        if (log.isDebugEnabled()) {
            log.debug("{}服务已将被注册", service.getInterfaceProvider().getName());
        }
    }

    @Override
    public InetSocketAddress lookup(String serviceName) {
        return null;
    }
}
